#!/usr/bin/python
from track import Track
import os
import cPickle as Pickle

def recup():
    from re import findall
    from urllib2 import urlopen
    try:
        fg = urlopen("http://www.radiofg.com/modules.php?name=Fg_Titres").read()
        REGEX = "<td class=\"textetrack\">\s+<div align=\"center\">\s+([\d+:]+).*</div></td>\s+<td class=\"textetrack\">(.*)</td>\s+<td class=\"textetrack\">(.*)</td>"
        list = findall(REGEX,fg)
        return list
    except:
        print 'can\'t download http://www.radiofg.com/modules.php?name=Fg_Titres'

def load():
    if os.path.isfile("tracklist"):
        trackliste = Pickle.load(open("tracklist", 'r'))
        return trackliste
        

def save(tracklist):
    Pickle.dump(tracklist, open("tracklist", 'w'))

def check(sartist,stitle):
    for track in tracklist:
        if track.artist == sartist and track.title == stitle : 
            return True

def search(query):
    querylist = [] 
    for track in tracklist:
        if track.artist.lower().find(query.lower()) != -1 or track.title.lower().find(query.lower()) != -1 :
            querylist.append(track)
    return querylist
    
tracklist = load()          
if not tracklist:
    tracklist=[]


for track in recup():
    if not check(track[2],track[1]):
       tracklist.append(Track(track[2],track[1]))
       print "ajoute " + track[2] + " " + track[1]
    else:
       print "ne pas ajouter " + track[2] + " " + track[1]

save(tracklist)

#while 1:
#    print search(raw_input())
